import { computed } from 'vue'
import { useRoute, useRouter, type RouteLocationMatched } from 'vue-router'

interface BreadcrumbItem {
  title: string
  path: string
}

export default function useBreadcrumb() {
  const route = useRoute()
  const router = useRouter()

  // 生成面包屑数据
  const breadcrumbs = computed(() => {
    const matched = route.matched.filter(
      (item) => item.meta && item.meta.breadcrumb !== false
    )

    return matched.map((match: RouteLocationMatched, index: number) => {
      // 处理动态路由参数
      const path = Object.keys(route.params).reduce(
        (acc, param) => acc.replace(`:${param}`, route.params[param] as string),
        match.path
      )

      // 生成最终路径
      const fullPath = getFullPath(match, index, matched)

      return {
        title: match.meta.breadcrumb || match.meta.title || match.name?.toString() || path,
        path: fullPath
      }
    })
  })

  // 获取完整路径
  const getFullPath = (match: RouteLocationMatched, index: number, matched: RouteLocationMatched[]) => {
    if (index === 0) return '/'

    // 处理嵌套路由路径
    const parent = matched[index - 1]
    const basePath = parent.path.endsWith('/')
      ? parent.path.slice(0, -1)
      : parent.path

    return `${basePath}/${match.path.startsWith('/')
      ? match.path.slice(1)
      : match.path}`
  }

  return {
    breadcrumbs
  }
}
